package com.lorizz.picpub.web.impl;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.lorizz.picpub.query.UpmQueries;
import com.lorizz.picpub.web.TokenGenerator;
import com.lorizz.upm.UserProfile;
import com.lorizz.upm.repository.Repository;

public class TokenGeneratorImpl implements TokenGenerator {

	private Repository upmRepository;
	private String key;
	private Cipher encryptCipher;
	private Cipher decryptCipher;


	public void setUpmRepository(Repository upmRepository) {
		this.upmRepository = upmRepository;
	}

	public void setKey(String key) {
		this.key = key;
	}
	
	public void init() throws Exception {
		byte[] raw = key.getBytes("ASCII");
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
		encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
	}

	@Override
	public String generate(UserProfile userProfile) {
		try {
			String data = userProfile.getName() + "|" + userProfile.getPassword();
			byte[] encrypted = encryptCipher.doFinal(data.getBytes("UTF-8"));
			return new BASE64Encoder().encode(encrypted);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public UserProfile evaluate(String token) {
		try {
            byte[] encrypted = new BASE64Decoder().decodeBuffer(token);
            String data = new String(decryptCipher.doFinal(encrypted), "UTF-8");
            String name = data.split("[\\|]")[0];
            String password = data.split("[\\|]")[1];
            return upmRepository.executeFirstOrDefault(UpmQueries.instance().userProfiles(name, password));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
